import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    //执行时间
    private long time;
    //持有一个Runnable
    private Runnable runnable;

    public MyTimerTask(Runnable runnable,long delay){
        this.time=System.currentTimeMillis()+delay;
        this.runnable=runnable;
    }

    //实际要执行的任务
    public void run(){
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
}

class MyTimer{
    //持有一个线程负责计时
    private Thread t=null;
    //任务队列——>优先级队列
    private PriorityQueue<MyTimerTask> queue =new PriorityQueue<>();
    //锁对象
    private Object locker=new Object();

    public void schedule(Runnable runnable,long delay){
        synchronized (locker) {
            //新建任务
            MyTimerTask task = new MyTimerTask(runnable, delay);
            //加入队列
            queue.offer(task);
            locker.notify();
        }
    }
    public void cancel(){
        t.interrupt();
    }
    public MyTimer(){
        t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            //阻塞
                            locker.wait();
                        }
                        //查看队首元素
                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() >= task.getTime()) {
                            queue.poll();
                            task.run();
                        } else {
                            //阻塞
                            locker.wait(task.getTime()-System.currentTimeMillis());
                        }
                    }
                } catch (InterruptedException e) {
                    break;
                }
            }
        });
        t.start();
    }
}
public class ThreadDemo5{
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer=new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(3000);
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(2000);
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(1000);
            }
        },1000);

        Thread.sleep(4000);
        timer.cancel();
    }
}